package cn.edu.zut.soft.graduate.controller.admin;

import cn.edu.zut.soft.basic.core.model.bo.CommonResult;
import cn.edu.zut.soft.graduate.base.utils.RandomFileUtil;
import cn.edu.zut.soft.graduate.core.constant.DeclareStatus;
import cn.edu.zut.soft.graduate.core.constant.InfoType;
import cn.edu.zut.soft.graduate.core.constant.Role;
import cn.edu.zut.soft.graduate.core.constant.config.IKEY;
import cn.edu.zut.soft.graduate.core.design.BasicInfoStrategy;
import cn.edu.zut.soft.graduate.core.model.Impl.CompanyProjectRequest;
import cn.edu.zut.soft.graduate.core.model.Impl.Identity;
import cn.edu.zut.soft.graduate.core.query.CompanyProjectRequestQuery;
import cn.edu.zut.soft.graduate.core.query.IdentityQuery;
import cn.edu.zut.soft.graduate.core.vo.LoginVO;
import cn.edu.zut.soft.graduate.core.vo.UserDescVO;
import cn.edu.zut.soft.graduate.groupCenter.bo.GroupBO;
import cn.edu.zut.soft.graduate.topicCenter.bo.CompanyProjectRequestBO;
import cn.edu.zut.soft.graduate.topicCenter.pojo.ReplyCompanyProject;
import cn.edu.zut.soft.graduate.userCenter.bo.IdentityBO;
import cn.edu.zut.soft.graduate.userCenter.bo.InfoBO;
import cn.edu.zut.soft.graduate.userCenter.bo.StudentBO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.*;

/**
 * <p>文件名称：AdminStudentController.java</p>
 * <p>文件描述：</p>
 * <p>版权所有： 版权所有(C)2011-2099</p>
 * <p>公   司： 口袋购物 </p>
 * <p>内容摘要： </p>
 * <p>其他说明： </p>
 * <p>完成日期：16/10/26 上午1:24</p>
 *
 * @author yangxiaotian@weidian.com
 * @version 1.0
 */
@RequestMapping("/admin")
@Controller
public class AdminStudentController {

    @Resource
    private CompanyProjectRequestBO companyProjectRequestBO;

    @Resource
    private IdentityBO identityBO;

    @Resource
    private GroupBO groupBO;

    @Resource
    private StudentBO studentBO;

    @Resource
    private InfoBO infoBO;


    @Value("#{commonProp['randomDrawingFilePath']}")
    private String randomDrawingFilePath;

    /**
     * 功能描述:学生自拟题目小组分配
     *
     * @param model
     * @return
     */
    @RequestMapping("/toCompany")
    public ModelAndView toCompany(Map<String, Object> model) {
        IdentityQuery identityQuery = new IdentityQuery();
        //检索所有的教师
        identityQuery.setLimit(Integer.MAX_VALUE);
        identityQuery.setRole(Role.tea);
        model.put("teaList", JSON.toJSON(identityBO.findByQuery(identityQuery).getData()));
        return new ModelAndView("/adminE/companyGroup", model);
    }

    /**
     * 功能描述:校外题目小组申请列表
     *
     * @param request
     * @param companyQuery
     * @return
     */
    @ResponseBody
    @RequestMapping("/companyList")
    public CommonResult companyList(HttpServletRequest request, CompanyProjectRequestQuery companyQuery) {
        if (companyQuery.getStatus() == null) {
            companyQuery.setStatusList(Arrays.asList(DeclareStatus.ING, DeclareStatus.YES, DeclareStatus.NO));
        }
        return companyProjectRequestBO.findByQuery(companyQuery);
    }

    /**
     * 功能描述:校外题目小组申请详细信息
     *
     * @param id
     * @param groupId
     * @return
     */
    @ResponseBody
    @RequestMapping("/companyInfo")
    public CommonResult companyInfoById(@RequestParam("id") Integer id, @RequestParam("groupId") Integer groupId) {
        if (id == null) {
            return CommonResult.errorReturn("System.error");
        }
        if (groupId == null) {
            return CommonResult.errorReturn("System.error");
        }
        CompanyProjectRequestQuery companyQuery = new CompanyProjectRequestQuery();
        companyQuery.setIds(Collections.singletonList(id));
        companyQuery.setGroupId(groupId);
        CommonResult<List<CompanyProjectRequest>> company = companyProjectRequestBO.findByQuery(companyQuery);
        return CommonResult.successReturn(company.getData());
    }

    /**
     * 功能描述:分配校外题目小组学生指导教师
     *
     * @param request
     * @param teaId
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/assignCompanyTea")
    public CommonResult agreeCompanyAssign(HttpServletRequest request, @RequestParam("teaId") Integer teaId, @RequestParam("id") Integer id) {
        LoginVO session = (LoginVO) request.getSession().getAttribute("user");
        ReplyCompanyProject replyCompanyProject = new ReplyCompanyProject();
        replyCompanyProject.setRequestId(id);
        replyCompanyProject.setTeacherId(teaId);
        replyCompanyProject.setDeclareStatus(DeclareStatus.YES);
        return CommonResult.successReturn(companyProjectRequestBO.successRequest(session, replyCompanyProject));
    }

    /**
     * 功能描述: 为教师分配学生<校内 未申请校外>
     *
     * @param request
     * @param teaId
     * @param groupId
     * @return
     */
    @ResponseBody
    @RequestMapping("/assignOneGrop")
    public CommonResult assignOneGroup(HttpServletRequest request, @RequestParam("teaId") Integer teaId, @RequestParam("groupId") Integer groupId) {
        if (teaId == null || groupId == null) {
            return CommonResult.errorReturn("System error");
        }
        LoginVO session = (LoginVO) request.getSession().getAttribute("user");
        if (session == null) {
            return CommonResult.errorReturn("请重新登录!");
        }
        return studentBO.assignStuGrouop(session, teaId, groupId);
    }

    @ResponseBody
    @RequestMapping("/createOneGroup")
    public CommonResult createOneGroup(HttpServletRequest request) {
        LoginVO session = (LoginVO) request.getSession().getAttribute("user");
        if (session == null) {
            return CommonResult.errorReturn("请重新登录!");
        }
        List<UserDescVO> result = studentBO.noGroupInstantiate(session);
        return CommonResult.successReturn(result);
    }

    @RequestMapping(value = "/randomDrawing")
    public ModelAndView randomDrawing() {
        return new ModelAndView("/adminE/random/randomDrawing");
    }

    @ResponseBody
    @RequestMapping("/detectionMidRan")
    public CommonResult detectionMidRan() {
        File file = new File(randomDrawingFilePath);
        if (!file.exists()) {
            return CommonResult.successReturn(Boolean.FALSE);
        }
        StringBuilder sb = new StringBuilder();
        RandomFileUtil.readFile(file, sb);
        JSONObject input = JSONObject.parseObject(sb.toString());
        Boolean a = input.getBoolean("use");
        if (a != null) {
            return CommonResult.successReturn(a);
        } else {
            return CommonResult.errorReturn("文件损坏");

        }
    }

    @ResponseBody
    @RequestMapping(value = "/saveMidRan",method = RequestMethod.POST)
    public CommonResult saveMidRan(HttpSession session) {
        LoginVO loginVO = (LoginVO) session.getAttribute(IKEY.USER);
        File file = new File(randomDrawingFilePath);
        if (!file.exists()) {
            return CommonResult.successReturn(Boolean.FALSE);
        }
        StringBuilder sb = new StringBuilder();
        RandomFileUtil.readFile(file, sb);
        JSONObject input = JSONObject.parseObject(sb.toString());
        List data = input.getObject("data",List.class);
        Set<Integer> ids = new HashSet<>(data.size());
        for (Object userDescVO:data){
            ids.add(((JSONObject)userDescVO).getObject("identity", Identity.class).getId());


        }
        CommonResult result = infoBO.saveBatch(new BasicInfoStrategy(InfoType.GRADE, IKEY.MID, IKEY.MID), ids, loginVO.getName());;
        if (result.isSuccess()) {
            input.put("use", false);
            RandomFileUtil.writerFile(file, input);
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("/openGradeNull")
    public CommonResult openGradeNullStudent(IdentityQuery identityQuery){
        return identityBO.getOpenGradeNull(identityQuery);
    }

}
